package com.example.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

/**
 * The type Jwt utils.
 */
public class JwtUtils {

    /**
     *  通过有效时间
     */
    private static final int DAYS = 30;

    /**
     * 密钥（需要后端严密保存）
     */
    private static final String SECRET_KEY = "1032227283@qq.com";

    /**
     * 生成token header.payload.sing
     *
     * @param map the map
     * @return the string
     */
    public static String getToken(Map<String,String> map){
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,DAYS);
        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();
        //payload
        map.forEach(builder::withClaim);
        //生成token，头部默认jwt和Base64编码
        return builder.withExpiresAt(instance.getTime())   //设置过期时间
                .sign(Algorithm.HMAC256(SECRET_KEY));
    }

    /**
     * 验证 token 合法性
     *
     * @param token the token
     * @return the decoded jwt
     */
    public static DecodedJWT verify(String token){
        return JWT.require(Algorithm.HMAC256(SECRET_KEY)).build().verify(token);
    }

}
